<script setup>

import MySelect from "@/components/constant/mySelect.vue";
import {getProjectList} from "@/api/httpApi/projectApi.js";
import {successCode} from "@/api/httpApi/base/http.js";
import {constantStore} from "@/stores/constantStore.js";
import {getCommodityCategoryList} from "@/api/httpApi/commodityCategoryApi.js";
import {delListApi, getOrderList, reSendApi} from "@/api/httpApi/orderApi.js";
import {error, success} from "@/api/myMessage.js";
import {onMounted, ref, reactive} from "vue";
import {portalUrl} from "@/api/const.js";
import MyTag from "@/components/constant/myTag.vue";
import {userStore} from "@/stores/userStore.js";
import {getUserList} from "@/api/httpApi/userApi.js";

const shortcuts = [
  {
    text: '最近一天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 1)
      return [start, end]
    },
  },
  {
    text: '最近三天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 3)
      return [start, end]
    },
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
  {
    text: '最近一年',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 12)
      return [start, end]
    },
  },
]

const timeValue = ref([]);
const keyWord = ref();
const projectId = ref();
const categoryId = ref();
const userId = ref();
const state = ref("2");

onMounted(() => {
  getOrderInfoList();
  initProject();
  initCategory();
  initUserList();
})

const categorySelect = ref();
const projectSelect = ref();

function initProject() {
  getProjectList().then((res) => {
    if (res.code === successCode) {
      console.log()
      projectSelect.value = constantStore().listToSelect(res.data, "name", "id");
    }
  })
}

function initCategory() {
  getCommodityCategoryList(projectId.value).then((res) => {
    if (res.code === successCode) {
      categorySelect.value = constantStore().listToSelect(res.data, "name", "id");
    }
  })
}

let userSelect = ref({});

function initUserList() {
  getUserList(1, 99999).then(res => {
    if (res.code === successCode) {
      userSelect.value = constantStore().listToSelect(res.data.content, "name", "id");
    }
  })
}

const orderInfoList = ref();

const orderInfoLoading = ref(true);

function getOrderInfoList() {
  orderInfoLoading.value = true;
  let startTime = timeValue.value && timeValue.value[0] ? timeValue.value[0].getTime() : "";
  let endTime = timeValue.value && timeValue.value[1] ? timeValue.value[1].getTime() : "";
  getOrderList(pageObj.value.currentPage, pageObj.value.pageSize, projectId.value, categoryId.value, state.value, keyWord.value, startTime, endTime, userId.value).then(res => {
    if (res.code === successCode) {
      constantStore().copyPage(pageObj, res.data);
      orderInfoList.value = res.data.content;
    }
    orderInfoLoading.value = false;
  })
}

let pageObj = ref({
  currentPage: 1,
  pageSize: 23,
  totalPages: 0,
  totalCount: 0,
  first: false,
  last: false,
})

function handleSizeChange() {
  getOrderInfoList();
}

function clearSearch() {
  timeValue.value = [];
  keyWord.value = "";
  projectId.value = "";
  categoryId.value = "";
  state.value = "";
  getOrderInfoList();
}

function doSearch() {
  getOrderInfoList();
}

const thisCommodityInfo = ref();
const commodityInfoShow = ref(false);

function showCommodityDialog(commodity) {
  thisCommodityInfo.value = commodity;
  commodityInfoShow.value = true;
}

function moveToUser(user) {
  location.href = (portalUrl + "/profile/" + user.id);
}

const reSendLoading = ref(false);

function handleReSend(index, item) {
  reSendLoading.value = true;
  reSendApi(item).then(res => {
    if (res.code === successCode) {
      success(res.message);
    } else {
      error(res.message);
    }
    getOrderInfoList();
    reSendLoading.value = false;
  })
}

const deleteIds = ref([])

function handleDelete(index, item) {
  deleteIds.value = [];
  deleteIds.value.push(item.id);
}

function handleSelectionChange(val) {
  deleteIds.value = [];
  val.forEach((item) => {
    deleteIds.value.push(item.id);
  })
}

function doDelete() {
  if (deleteIds.value.length === 0) {
    success("删除成功");
    return;
  }
  delListApi(deleteIds.value).then((res) => {
    if (res.code === successCode) {
      success(res.message);
    } else {
      error(res.message);
    }
    getOrderInfoList();
    deleteIds.value = [];
  })
}
</script>

<template>
  <div class="order-info-box">
    <div class="order-top">
      <div class="del">
        <el-popconfirm v-if="pageObj.totalCount > 0"
                       title="您确定删除选中项么？"
                       cancel-button-text="取消"
                       confirm-button-type="danger"
                       @confirm="doDelete"
                       confirm-button-text="删除">
          <template #reference>
            <el-button type="danger" style="margin-bottom: 1rem">批量删除</el-button>
          </template>
        </el-popconfirm>
      </div>
      <div class="key-input">
        <el-input v-model="keyWord" style="width: 18rem" placeholder="商品信息/描述" clearable/>
      </div>
      <div class="project">
        <my-select v-model="projectId" placeholder="选择商城" :option="projectSelect" @change-value="initCategory"/>
      </div>
      <div class="category">
        <my-select v-model="categoryId" placeholder="选择类别" :option="categorySelect"/>
      </div>
      <div class="user">
        <my-select v-model="userId" placeholder="选择消费用户" :option="userSelect"/>
      </div>
      <div class="state">
        <my-select v-model="state" placeholder="选择订单状态" :option='[ {value: "1" , label: "交易失败"}, {value: "2", label: "交易完成"},
                                                                       {value: "3",label: "等待发货"}, {value: "4",label: "等待签收"}]'/>
      </div>
      <div class="time">
        <el-date-picker
            format="YYYY-MM-DD HH:mm:ss"
            v-model="timeValue"
            type="datetimerange"
            :shortcuts="shortcuts"
            range-separator=" <--> "
            :arrow-control="true"
            start-placeholder="开始时间(最近操作时间)"
            end-placeholder="截止时间(最近操作时间)"/>
      </div>
      <div class="button">
        <el-button @click="clearSearch">清 空</el-button>
        <el-button type="primary" @click="doSearch">搜 索</el-button>
      </div>
    </div>
    <div class="order-content">
      <div class="content-table" v-loading="orderInfoLoading">
        <el-table :data="orderInfoList" empty-text="无数据"
                  @selection-change="handleSelectionChange"
                  lazy border stripe highlight-current-row>
          <el-table-column type="selection" width="55"/>
          <el-table-column align="center" label="商品名称" width="172" fixed="left">
            <template #default="scope">
              <div class="commodity-info" @click="showCommodityDialog(scope.row.commodity)">
                {{ scope.row.commodity.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="发货失败原因" align="center" prop="commodityMsg" width="400"/>
          <el-table-column label="总价" align="center" prop="money" width="100"/>
          <el-table-column label="数量" align="center" prop="count" width="80"/>
          <el-table-column label="质量" align="center" prop="multiplier" width="80"/>
          <el-table-column label="等级" align="center" prop="level" width="80"/>
          <el-table-column label="状态" align="center" width="100">
            <template #default="scope">
              <my-tag :data="scope.row.state"
                      :mapping='[ { type: "", data: "0", msg: "购物车中"},
                                    { type: "danger", data: "1", msg: "交易失败"},
                                    { type: "success", data: "2", msg: "交易完成"},
                                    { type: "warning",data: "3",msg: "等待发货"},
                                    { type: "primary",data: "4",msg: "等待签收"}]'/>
            </template>
          </el-table-column>
          <el-table-column label="是否删除" align="center" width="100">
            <template #default="scope">
              <my-tag :data="scope.row.delete"
                      :mapping='[ { type: "danger", data: "1", msg: "删除"},{ type: "success", data: "0", msg: "正常"}]'/>
            </template>
          </el-table-column>
          <el-table-column label="蓝图" align="center" prop="bluePic" width="80">
            <template #default="scope">
              <my-tag :data="scope.row.bluePic"
                      :mapping='[ { type: "danger",data: false,msg: "否",},
                                    { type: "success",data: true, msg: "是"}]'/>
            </template>
          </el-table-column>
          <el-table-column label="下单用户" align="center" prop="buyUserId" width="100">
            <template #default="scope">
              <div class="commodity-info" @click="moveToUser(scope.row.buyUser)"
                   v-if="scope.row.buyUser.name !== userStore().loginUser.name">
                {{ scope.row.buyUser.name }}
              </div>
              <div v-else>
                {{ scope.row.buyUser.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="收货用户" align="center" prop="toUserId" width="100">
            <template #default="scope">
              <div class="commodity-info" @click="moveToUser(scope.row.toUser)"
                   v-if="scope.row.toUser.name !== userStore().loginUser.name">
                {{ scope.row.toUser.name }}
              </div>
              <div v-else>
                {{ scope.row.toUser.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="收货地址" align="center" prop="address.name" width="300"/>
          <el-table-column label="下单时间" align="center" prop="createTime" width="160"/>
          <el-table-column label="最近操作时间" align="center" prop="updateTime" width="160"/>
          <el-table-column label="操 作" align="center" width="180" fixed="right">
            <template #default="scope">
              <el-button v-if="scope.row.state === '1'" size="small" type="success"
                         @click="handleReSend(scope.$index, scope.row)" :disabled="reSendLoading">
                重新发货
              </el-button>
              <el-popconfirm title="您确定删除么？"
                             cancel-button-text="取消"
                             confirm-button-type="danger"
                             @confirm="doDelete"
                             confirm-button-text="删除">
                <template #reference>
                  <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                    删 除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="order-page" v-if="pageObj.totalCount > 0">
          <el-pagination
              v-model:current-page="pageObj.currentPage"
              v-model:page-size="pageObj.pageSize"
              :page-sizes="[20, 50, 100, 200]"
              size="default"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageObj.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleSizeChange"
          />
        </div>
      </div>
    </div>
    <div class="order-dialog">
      <div class="commodity-info-box">
        <el-dialog v-model="commodityInfoShow" title="商品信息" width="500"
                   @before-close="thisCommodityInfo = {}">
          <div class="commodity-info">
            <div class="commodity-info-item commodity-name">
              {{ thisCommodityInfo.name }}
            </div>
            <div class="commodity-info-item commodity-image">
              <el-image :src="thisCommodityInfo.image"/>
            </div>
            <div class="commodity-info-item commodity-category">
              <span class="title">
                类别：
              </span>
              {{ thisCommodityInfo.commodityCategory.name }}
            </div>
            <div class="commodity-info-item commodity-project-name">
               <span class="title">
                 商店：
               </span>
              {{ thisCommodityInfo.projectName }}
            </div>
            <div class="commodity-info-item commodity-time">
              <span class="title">
                上架时间：
              </span>
              {{ thisCommodityInfo.createTime }}
            </div>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.order-info-box {
  user-select: none;

  .order-top {
    display: flex;
    flex-wrap: wrap; /* 允许换行 */
    justify-content: start;
    min-height: 6rem;
    padding: 2rem 1rem;
    border-bottom: #CDD0D6 dashed .2rem;
    user-select: none;
    background-color: var(--item-bgc);

    & > div {
      margin: 1rem;
    }
  }

  .order-content {
    margin-top: 1rem;
    background-color: var(--item-bgc);

    .content-table {

      .commodity-info {
        user-select: none;
        cursor: pointer;
      }

      .commodity-info:hover {
        text-decoration: underline;
        color: #409EFF;
      }
    }

    .order-page {
      padding: 2rem 0;
    }
  }

  .order-dialog {

    .commodity-info-box {

      .commodity-info {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .commodity-info-item {
          display: flex;
          align-items: center;
          padding: 1rem 0;

          .title {
            font-size: .8rem;
            font-weight: bolder;
          }
        }

        .commodity-name {
          font-size: 1.2rem;
          font-weight: bolder;
        }

        .commodity-image {
          width: 12rem;
          height: 12rem;
          padding: 0;
          user-select: none;
          border: solid .1rem #CDD0D6;
        }

        .commodity-category {
          font-size: 1rem;
        }

        .commodity-project-name {
          font-size: 1rem;
        }

        .commodity-time {
          font-size: 1rem;
        }
      }
    }
  }
}
</style>